<?php
declare (strict_types = 1);

namespace uctoo\middleware;

use uctoo\util\library\Dev;
use uctoo\util\library\Mpopen;
use EasyWeChat\Factory;

class Applet
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
            $applet = \catchAdmin\wechatopen\model\Applet::appInfo($request->user['aid']);
            if(!$applet){
                $result = [
                    'code' => 400,
                    'msg'  => '请重新登录',
                    'time' => $request->server('REQUEST_TIME'),
                    'data' => null,
                ];
                return Response::create($result, 'json', 200);
            }

            if(Dev::DEV_APP_ID === $applet['appid']){
                //开发模式
                $request->mapp = Dev::mpInstance();
            }else {
                $app = invoke(Mpopen::class);
                $mapp = $app->miniProgram($applet['appid'], $applet['refresh_token']);
                $mapp->config->add('env', $applet['env']);
                $request->mapp = $mapp;
            }

            $request->applet = $applet;

        return $next($request);
    }
}
